from datetime import datetime, timedelta


def divide_month_into_weeks(input_date, start=False):
    # 获取当月的第一天
    if start:
        first_day_of_month = input_date
    else:
        first_day_of_month = datetime(input_date.year, input_date.month, 1)
    # 获取当月的最后一天
    if input_date.month == 12:
        last_day_of_month = datetime(input_date.year, input_date.month, 31)
    else:
        next_month = first_day_of_month.replace(month=first_day_of_month.month + 1, day=1)
        last_day_of_month = next_month - timedelta(days=1)
    # 获取当月第一天是星期几（0表示周一，6表示周日）
    start_weekday = first_day_of_month.weekday()

    # 当月的第一周从当月的第一天开始
    week_start = first_day_of_month
    weeks = []

    # 计算第一周
    week_end = min(first_day_of_month + timedelta(days=6 - start_weekday), last_day_of_month)
    weeks.append((week_start, week_end))

    # 从下一周开始计算
    week_start = week_end + timedelta(days=1)
    while week_start < last_day_of_month:
        # 下一周的结束日期
        week_end = min(week_start + timedelta(days=6), last_day_of_month)
        weeks.append((week_start, week_end))
        week_start = week_end + timedelta(days=1)

    return weeks


def group_dates_by_months(start_date, end_date):
    current_date = start_date
    monthly_weeks = {}

    while current_date <= end_date:
        # 获取当前月份
        current_month = datetime(current_date.year, current_date.month, 1)

        # 如果当前月份不在字典中，则添加
        if current_month not in monthly_weeks:
            monthly_weeks[current_month] = []

        # 添加当前日期所在的周
        for week_start, week_end in divide_month_into_weeks(current_month):
            if current_date > week_start:
                monthly_weeks[current_month].append((week_start, week_end))
            elif end_date < week_end:
                monthly_weeks[current_month].append((week_start, end_date))
            else:
                monthly_weeks[current_month].append((week_start, week_end))

        # 移动到下一个月的第一天
        if current_date.month == 12:
            current_date = datetime(current_date.year + 1, 1, 1)
        else:
            current_date = datetime(current_date.year, current_date.month + 1, 1)

    return monthly_weeks

# 示例：获取从2023年2月到2024年10月每个月的每周范围
start_date = datetime(2023, 2, 2)
end_date = datetime(2024, 10, 10)
monthly_weeks = group_dates_by_months(start_date, end_date)
# 输出结果

print(monthly_weeks)
# for month, weeks in sorted(monthly_weeks.items()):
#     print(f"Month: {month.strftime('%Y-%m')}")
#     for week in weeks:
#         print(f"\tWeek from {week[0].strftime('%Y-%m-%d')} to {week[1].strftime('%Y-%m-%d')}")